package com.sf.dlb.service;

import com.sf.dlb.bean.ETHWalletResponseBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.UserDlbRecordInfo;
import com.sf.dlb.jpa.model.UserWalletInfo;
import com.sf.dlb.jpa.model.WalletEthAddressInfo;
import com.sf.dlb.jpa.model.WalletTopupInfo;
import com.sf.dlb.jpa.repository.UserDlbRecordRepository;
import com.sf.dlb.jpa.repository.UserWalletRepository;
import com.sf.dlb.jpa.repository.WalletEthAddressRepository;
import com.sf.dlb.jpa.repository.WalletTopupRepository;
import com.sf.dlb.utils.Arith;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.utils.StateToValueUtils;
import com.sf.dlb.vo.PageVO;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.vo.WalletTopupVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 充值记录表 service
 *
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class WalletTopupService {
    private Logger logger= LoggerFactory.getLogger(WalletTopupService.class);
    @Autowired
    private WalletTopupRepository walletTopupRepository;
    @Autowired
    private ETHWalletService ethWalletService;
    @Autowired
    private UserDlbRecordRepository userDlbRecordRepository;
    @Autowired
    private UserWalletRepository userWalletRepository;
    @Autowired
    private WalletEthAddressRepository walletEthAddressRepository;
    /**
     * 充值记录
     * @param userId
     * @param page
     * @param size
     * @return
     */
    public ResultVO list(String userId,int page,int size){
        logger.info("list start userId={},page={},size={}",userId,page,size);
        //分页查询
        Sort sort=new Sort(Sort.Direction.DESC,"topupTime");
        Pageable pageable= new PageRequest(page,size,sort);
        Page<WalletTopupInfo> pageAll=walletTopupRepository.findByUserIdAndDelFlag(userId,"0",pageable);
        List<WalletTopupInfo> extractInfoList=pageAll.getContent();
        //封装VO
        List<WalletTopupVO> walletTopupVOS=new ArrayList<>();
        for (WalletTopupInfo walletTopupInfo:extractInfoList) {
            WalletTopupVO walletExtractVO=new WalletTopupVO();
            BeanUtils.copyProperties(walletTopupInfo,walletExtractVO);
            walletExtractVO.setStateValue(StateToValueUtils.switchTopupStateValue(walletTopupInfo.getState()));
            walletExtractVO.setTopupTime(walletTopupInfo.getTopupTime().getTime());
            walletTopupVOS.add(walletExtractVO);
        }
        PageVO pageVO=new PageVO();
        pageVO.setDataList(walletTopupVOS);
        pageVO.setPageSize(size);
        pageVO.setCurrentPages(page+1);//默认从0开始，返回前端要+1;
        pageVO.setFirstPage(pageAll.isFirst());
        pageVO.setLastPage(pageAll.isLast());
        pageVO.setTotalElements(pageAll.getTotalElements());
        pageVO.setTotalPages(pageAll.getTotalPages());
        return ResultVOUtil.success(pageVO);
    }

    /**
     * 查询以太坊充值记录保存到本地
     */
    @Transactional
    public void queryTopupSaveLocal(String userId){
        logger.info("queryTopupSaveLocal start userId={}",userId);
        WalletEthAddressInfo walletEthAddressInfo=walletEthAddressRepository.findByUserIdAndDelFlag(userId,"0");
        if(null==walletEthAddressInfo){
            logger.info("queryTopupSaveLocal null==walletEthAddressInfo ");
            return;
        }
        //查询用户以太坊，是否有充值记录，有的话，存入数据库，
        List<ETHWalletResponseBean> ethWalletResponseBeans=ethWalletService.topUpRecrd(walletEthAddressInfo.getAddress());
        if(ethWalletResponseBeans!=null&&ethWalletResponseBeans.size()>0) {
            //查询本地是否已经存在了，避免插入重复的；
            List<WalletTopupInfo> walletTopupInfos1=walletTopupRepository.findByUserIdAndDelFlag(userId,"0");
            List<WalletTopupInfo> walletTopupInfos = new ArrayList<>();//钱包充值信息
            List<UserDlbRecordInfo> userDlbRecordInfos=new ArrayList<>();//用户dlb流水
            for (ETHWalletResponseBean ethWalletResponseBean : ethWalletResponseBeans) {
                boolean falg=true;
                //充值记录是否已存在
                for (WalletTopupInfo walletTopupInfo:walletTopupInfos1) {
                    if(ethWalletResponseBean.getTransactionHash().equals(walletTopupInfo.getTransactionHash())){
                        falg=false;
                        break;
                    }
                }
                if(falg) {
                    WalletTopupInfo walletTopupInfo = new WalletTopupInfo();
                    walletTopupInfo.setUserId(userId);
                    walletTopupInfo.setForAddress(ethWalletResponseBean.getFrom());
                    walletTopupInfo.setToAddress(ethWalletResponseBean.getTo());
                    walletTopupInfo.setTransactionHash(ethWalletResponseBean.getTransactionHash());
                    Long timestamp = Long.valueOf(ethWalletResponseBean.getTimestamp() + "000");//时间戳转毫秒
                    walletTopupInfo.setTopupTime(new Date(timestamp));
                    walletTopupInfo.setCount(Double.valueOf(ethWalletResponseBean.getCount()));
                    walletTopupInfo.setState("0");//能从以太坊查到，说明都成功了
                    walletTopupInfo.setCreateDate(new Date());
                    walletTopupInfo.setUpdateDate(new Date());
                    walletTopupInfos.add(walletTopupInfo);
                    //dlb流水
                    UserDlbRecordInfo userDlbRecordInfo = new UserDlbRecordInfo();
                    userDlbRecordInfo.setUserId(userId);
                    userDlbRecordInfo.setSource(ResponseConstant.source_type_topup);
                    userDlbRecordInfo.setSourceDesc(ResponseConstant.source_type_topup_value+":TransactionHash:"+ethWalletResponseBean.getTransactionHash());
                    userDlbRecordInfo.setDlbNumber(Double.valueOf(ethWalletResponseBean.getCount()));
                    userDlbRecordInfo.setDlbType(ResponseConstant.type_add);
                    userDlbRecordInfo.setCreateDate(new Date());
                    userDlbRecordInfo.setUpdateDate(new Date());
                    userDlbRecordInfos.add(userDlbRecordInfo);
                }
            }
            walletTopupRepository.save(walletTopupInfos);
            logger.info("queryTopupSaveLocal ethWalletResponseBeans={},walletTopupInfos={}",ethWalletResponseBeans.size(),walletTopupInfos.size());
            //dlb流水添加
            userDlbRecordRepository.save(userDlbRecordInfos);
            logger.info("queryTopupSaveLocal userDlbRecordInfos={}",userDlbRecordInfos.size());
            //更新钱包,充值默认是已锁定
            Double countD=0.0;
            for (WalletTopupInfo walletTopupInfo:walletTopupInfos) {
                countD+=Double.valueOf(walletTopupInfo.getCount());
            }
            if(countD>0){
                UserWalletInfo userWalletInfo=userWalletRepository.findByUserIdAndDelFlag(userId,"0");
                Double lockDlb=userWalletInfo.getLockDlb();
                lockDlb=(null==lockDlb?0.0:lockDlb);
                userWalletInfo.setLockDlb(Arith.add(lockDlb,countD));
                userWalletInfo.setUpdateDate(new Date());
                userWalletRepository.save(userWalletInfo);
                logger.info("queryTopupSaveLocal userWalletInfo={}", GsonUtils.getInstance().toJson(userWalletInfo));
            }
        }
    }
}